/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package generic.net;

import generic.net.Response;
import generic.net.Request;
import generic.net.PendingResponse;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author adam
 */
public class PendingRequestTest {
    private PendingResponse pr;
    private Request request;
    private Response response;

    public PendingRequestTest() {
    }

    @Before
    public void init() {
        request = new Request();
        response = new Response();
        response.setID(request.getID());
        pr = new PendingResponse(request);
    }

    @After
    public void dispose() {
        pr = null;
    }

    /**
     * Test of getRequest method, of class PendingRequest.
     */
    @Test
    public void testGetRequest() {
        System.out.println(":::Testing GetRequest:::");
        Assert.assertEquals(pr.getRequest(), request);
    }

    /**
     * Test of getResponse method, of class PendingRequest.
     */
    @Test
    public void testGetResponse() {
        System.out.println(":::Testing GetResponse:::");
        // We will start a new therad to send the response in a second.
        new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {}
                pr.setResponse(response);
            }
        }).start();

        // Then all we need to do is wait for that thread to respond :)

        Assert.assertEquals(pr.getResponse(), response);
    }

    /**
     * Test of getResponse method, of class PendingRequest.
     */
    @Test
    public void testGetResponse_wtimeout() {
        System.out.println(":::Testing GetResponse With Timeouts:::");
        // We will start a new therad to send the response in a second.
        new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {}
                pr.setResponse(response);
            }
        }).start();

        // First we test the responses timeout properly
        // and return null when we dont wait long enough.
        Assert.assertEquals(pr.getResponse(1), null);

        // Then test that they still work, provided a response
        // happens in a timely fashion.
        Assert.assertEquals(pr.getResponse(10000), response);
    }

    /**
     * Test of setResponse method, of class PendingRequest.
     */
    @Test
    public void testSetResponse() {
        System.out.println(":::Testing SetResponse:::");
        pr.setResponse(response);
        assertEquals(pr.getResponse(), response);
    }

}